package com.ruoyi.web.controller.exam;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.vo.PageResult;
import com.ruoyi.exam.domain.ExamScores;
import com.ruoyi.exam.serive.IExamScoreService;
import com.ruoyi.exam.vo.ExamScoreListReqVO;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.exam.vo.ExamScoresVO;
import com.ruoyi.web.controller.exam.vo.ExamUnrealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/exam/score")
public class ExamScoreController extends BaseController {
    @Autowired
    private IExamScoreService scoreService;
    @Autowired
    private ISysUserService userService;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('exam:score:list')")
    public TableDataInfo page(ExamScoreListReqVO reqVO){
        if(!StrUtil.isBlank(reqVO.getUserNickname())){
            SysUser user = userService.selectUserByUserName(reqVO.getUserNickname());
            if(user == null){
                return getDataTable(new ArrayList<>(0));
            }
            reqVO.setUid(user.getUserId());
        }
        PageResult<ExamScores> pageResult = scoreService.pageScores(reqVO);
        PageResult<ExamScoresVO> tmp = new PageResult<>(pageResult.getPage(), pageResult.getPageSize(), pageResult.getTotal());
        if(pageResult.getTotal() > 0) {
            Long[] uids = pageResult.getData().stream().map(u -> u.getUid()).toArray(Long[]::new);
            List<SysUser> users = userService.selectUserByIds(uids);
            Map<Long, SysUser> map = users.stream().collect(Collectors.toMap(SysUser::getUserId, u -> u));

            List<ExamScoresVO> list = pageResult.getData().stream().map(s -> {
                ExamScoresVO vo = new ExamScoresVO();
                vo.setScores(s);
                SysUser user;
                if((user = map.get(s.getUid())) != null){
                    vo.setNickname(user.getNickName());
                }
                return vo;
            }).collect(Collectors.toList());
            tmp.addAll(list);
        }

        return getDataTable(tmp.convertToPage());
    }
}
